﻿#!/usr/bin/python3
# coding=utf-8
import random
import re
import sys
import json
from datetime import datetime

import requests


class iciba:
    # 初始化
    def __init__(self, wechat_config, template_params):
        self.appid = wechat_config['appid'].strip()
        self.appsecret = wechat_config['appsecret'].strip()
        self.access_token = ''
        self.template_params = template_params

    # 错误代码
    def get_error_info(self, errcode):
        return {
            40013: '不合法的 AppID ，请开发者检查 AppID 的正确性，避免异常字符，注意大小写',
            40125: '无效的appsecret',
            41001: '缺少 access_token 参数',
            40003: '不合法的 OpenID ，请开发者确认 OpenID （该用户）是否已关注公众号，或是否是其他公众号的 OpenID',
            40037: '无效的模板ID',
        }.get(errcode, 'unknown error')

    # 打印日志
    def print_log(self, data, openid=''):
        errcode = data['errcode']
        errmsg = data['errmsg']
        if errcode == 0:
            print(' [INFO] send to %s is success' % openid)
        else:
            print(' [ERROR] (%s) %s - %s' % (errcode, errmsg, self.get_error_info(errcode)))
            if openid != '':
                print(' [ERROR] send to %s is error' % openid)

    # 获取access_token
    def get_access_token(self, appid, appsecret):
        url = 'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=%s&secret=%s' % (
            appid, appsecret)
        r = requests.get(url)
        data = json.loads(r.text)
        if 'errcode' in data:
            self.print_log(data)
        else:
            self.access_token = data['access_token']

    # 获取用户列表
    def get_user_list(self):
        if self.access_token == '':
            self.get_access_token(self.appid, self.appsecret)
        url = 'https://api.weixin.qq.com/cgi-bin/user/get?access_token=%s&next_openid=' % self.access_token
        r = requests.get(url)
        data = json.loads(r.text)
        if 'errcode' in data:
            self.print_log(data)
        else:
            openids = data['data']['openid']
            return openids

    # 发送消息
    def send_msg(self, openid, template_id, iciba_everyday):
        msg = {
            'touser': openid,
            'template_id': template_id,
            # "url": "http://weixin.qq.com/download",
            'data': iciba_everyday
        }
        json_data = json.dumps(msg)
        if self.access_token == '':
            self.get_access_token(self.appid, self.appsecret)
        url = 'https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=%s' % self.access_token
        r = requests.post(url, json_data)
        print(msg)
        return json.loads(r.text)

    # 获取爱词霸每日一句
    def get_iciba_everyday(self):
        temp_love_list = [
            {'content': "Don't stop. Don't hide. Follow the light, and you'll find tomorrow.",
             'note': '不要停下，不要逃避，沿着光明前行，你会找到明天。'},
            {
                'content': 'Since you are like no other being ever created since the beginning of time, you are incomparable.',
                'note': '因为你和有史以来任何人类都不相同，所以你是无可比拟的。'},
            {'content': 'When the lord closes a door, somewhere he opens a window.',
             'note': '当主关上了一扇门，就会在别处打开一扇窗。'},
            {'content': 'All friendship changes, but for the good ones it will only make it stronger. ',
             'note': '所有的友情都会变，但有的改变会让其变得强大。'},
            {
                'content': 'Since you are like no other being ever created since the beginning of time, you are incomparable.',
                'note': '因为你和有史以来任何人类都不相同，所以你是无可比拟的。'},
        ]
        # 金山词霸地址
        address = "http://open.iciba.com/dsapi"
        headers = {
            "User-Agent": "Mozilla/5.0 (iPhone; CPU iPhone OS 11_3 like Mac OS X) AppleWebKit/604.1.34 (KHTML, like Gecko) CriOS/66.0.3359.122 Mobile/15E216 Safari/604.1"
        }
        # 发送请求
        response = requests.get(address, headers=headers)
        if response.status_code == 200:
            temp_text = response.json()
        else:
            temp_text = temp_love_list[random.randint(1, 5)]

        return temp_text

    def get_caihongpi(self):
        temp_love = [
            {"code": 200, "msg": "success", "newslist": [{"content": "多谢你如此精彩耀眼，做我平淡岁月里的星辰"}]},
            {'code': 200, 'msg': 'success', 'newslist': [{'content': '以后的每一分钟，我会当你的守卫，陪你走向每一个结尾。'}]},
            {'code': 200, 'msg': 'success', 'newslist': [{'content': '突然明白这世上所有丹青水墨，山遥水阔，都是为了铺垫你这人间绝色。'}]},
            {'code': 200, 'msg': 'success', 'newslist': [{'content': f'{self.girl_name}最大的遗憾就是不能亲吻自己的脸。'}]},
        ]
        params = {
            "key": self.tian_caihongpi_key
        }
        headers = {'Content-type': 'application/x-www-form-urlencoded'}
        response = requests.post('http://api.tianapi.com/caihongpi/index', params, headers)
        if response.status_code == 200:
            love_text = response.json().get("newslist")[0].get("content")
            if love_text.rfind("xxx") != -1:
                love_text = love_text.replace("xxx", self.girl_name)
            if love_text.rfind("XXX") != -1:
                love_text = love_text.replace("XXX", self.girl_name)
        else:
            love_text = temp_love[random.randint(1, 4)].get("newslist")[0].get("content")

        return love_text

    def get_weather(self):
        response = requests.get(
            f"https://api.map.baidu.com/weather/v1/?district_id={self.district_id}&data_type=all&ak={self.weather_ak}")
        weather = {}
        if response.status_code == 200:
            weather_result = response.json().get("result")
            region = weather_result.get("location")
            weather["location"] = region.get("province") + region.get("city") + region.get("name") + "区"

            now_forecasts = weather_result.get("forecasts")[0]
            weather["text_day"] = now_forecasts.get("text_day").strip()
            if "雨" in weather["text_day"]:
                weather["text_day"] += " 记得带上雨伞哦"
            weather["text_night"] = now_forecasts.get("text_night").strip()
            if "雨" in weather["text_night"]:
                weather["text_night"] += " 记得带上雨伞哦"
            weather["high_temperature"] = now_forecasts.get("high")
            weather["low_temperature"] = now_forecasts.get("low")
        else:
            # 保险起见 写一个常驻地址
            weather["location"] = "中国"
            weather["text_day"] = "晴"
            weather["text_night"] = "晴"
            weather["high_temperature"] = 30
            weather["low_temperature"] = 20

        return weather

    def get_time(self):
        week_list = ["星期一", "星期二", "星期三", "星期四", "星期五", "星期六", "星期日"]
        current_time = datetime.now()
        return {"week": week_list[current_time.weekday()], "date": current_time.strftime("%Y-%m-%d")}

    def get_birthday_interval(self, original_date):
        birthday = datetime.strptime(original_date, "%Y-%m-%d")
        today = datetime.strptime(datetime.now().strftime("%Y-%m-%d"), "%Y-%m-%d")
        birth = datetime(
            year=today.year,
            month=birthday.month,
            day=birthday.day
        )

        if birth < today:
            birth = datetime(
                year=today.year + 1,
                month=birthday.month,
                day=birthday.day
            )

        distance = (birth - today).days
        if distance == 0:
            return "大寿星大宝贝！！ 生日快乐！！！！！"
        elif distance == 1:
            return "高能预警！明天就是宝贝的生日啦！！！"
        else:
            return distance

    def get_data(self, template_id):
        self.weather_ak = self.template_params[template_id].get('weather_ak')
        self.tian_caihongpi_key = self.template_params[template_id].get('tian_caihongpi_key')
        self.target_lianAi = self.template_params[template_id].get('target_lianAi')
        self.target_shengRi = self.template_params[template_id].get('target_shengRi')
        birthday = datetime.strptime(self.target_shengRi, "%Y-%m-%d")
        today = datetime.strptime(datetime.now().strftime("%Y-%m-%d"), "%Y-%m-%d")
        birth = datetime(
            year=today.year,
            month=birthday.month,
            day=birthday.day
        )

        if birth < today:
            birth = datetime(
                year=today.year + 1,
                month=birthday.month,
                day=birthday.day
            )
        self.mark = self.template_params[template_id].get('mark')
        self.girl_name = self.template_params[template_id].get('girl_name')
        self.district_id = self.template_params[template_id].get('district_id')

        weather = self.get_weather()
        current_time = self.get_time()
        # truth_word = self.get_iciba_everyday()

        caihongpi0 = self.get_caihongpi()

        result =  {
            "riqi": {"value": f"{current_time.get('date')} {current_time.get('week')}"},
            "day_tianqi": {"value": weather.get("text_day")},
            "night_tianqi": {"value": weather.get("text_night")},
            "region": {"value": weather.get("location")},
            "low_and_high": {"value": F"{weather.get('low_temperature')} {weather.get('high_temperature')}"},
            "high": {"value": weather.get("high_temperature")},
            "caihongpi0": {"value": caihongpi0},
            "caihongpi1": {"value": ""},
            "caihongpi2": {"value": ""},
            "caihongpi3": {"value": ""},
            "lianai": {"value":  "%s%s" % (str((datetime.now() - datetime.strptime(self.target_lianAi, "%Y-%m-%d")).days), " "+self.mark if self.mark else '')},
            "shengri": {"value": self.get_birthday_interval(self.target_shengRi)},
            # "jinju": {
            #     "value": f"\r\n{truth_word.get('content')}\r\n{truth_word.get('note')}"},
            "linzhen": {"value": "278"},
            "beizhu": {"value": f"{self.mark}" if self.mark else ""}
        }

        if len(caihongpi0) > 20:
            for index, str_ in enumerate(range(0, len(caihongpi0), 20)):
                re_sub_space = re.sub(r"\s{2,}", "", caihongpi0[index*20:index+((index+1) * 20)])
                result[f"caihongpi{index}"] = {"value": re_sub_space}
        return result


    # 为设置的用户列表发送消息
    def send_everyday_words(self, openids):
        for contartain in openids:
            openid = contartain.get("open_id")
            # del everyday_words['jinju']
            everyday_words = self.get_data(contartain.get("template_id"))
            result = self.send_msg(openid, contartain.get("template_id"), everyday_words)
            self.print_log(result, openid)

    # 执行
    def run(self, openids=[]):
        if openids == []:
            # 如果openids为空，则遍历用户列表
            # openids = self.get_user_list()
            print("openids为空")
            return
        # 根据openids对用户进行群发
        self.send_everyday_words(openids)
